/*
 * @Author: cyfqyb
 * @Date: 2023-11-06 10:24:09
 * @LastEditors: cyfqyb cy15770703229@163.com
 * @LastEditTime: 2023-11-06 16:03:56
 * @FilePath: \ImBackend\src\utils\index.ts
 * @Description: 介绍
 */
//写一个节流函数
export function throttle<T extends (...args: any[]) => void>(func: T, delay: number): T {
	let lastInvokeTime = 0;
	let timeoutId: NodeJS.Timeout;

	return function (this: any, ...args: any[]) {
		console.log(123456);

		const now = Date.now();
		const elapsedTime = now - lastInvokeTime;

		const invokeFunction = () => {
			lastInvokeTime = Date.now();
			func.apply(this, args);
		};

		if (elapsedTime >= delay) {
			clearTimeout(timeoutId);
			invokeFunction();
		} else {
			clearTimeout(timeoutId);
			timeoutId = setTimeout(invokeFunction, delay - elapsedTime);
		}
	} as T;
}
//写一个防抖函数
export function debounce<T extends (...args: any[]) => void>(func: T, delay: number): T {
	let timeoutId: NodeJS.Timeout;

	return function (this: any, ...args: any[]) {
		const invokeFunction = () => {
			func.apply(this, args);
		};

		clearTimeout(timeoutId);
		timeoutId = setTimeout(invokeFunction, delay);
	} as T;
}
//文件上传函数
export function imgUpload() {
	return new Promise((resolve, reject) => {
		const input = document.createElement("input");
		input.type = "file";
		input.accept = "image/*";
		input.onchange = e => {
			const file = (e as any).target!.files[0];
			if (!file) {
				reject("请选择图片");
				return;
			}
			const reader = new FileReader();
			reader.readAsDataURL(file);
			reader.onload = e => {
				const result = e.target?.result;
				if (!result) {
					reject("读取图片失败");
					return;
				}
				resolve(result);
			};
		};
		input.click();
	});
}
